<?php
defined('_JEXEC') or die('Restricted access');

/**
 * Description of Tools
 * 
 * @todo 
 *     
 * @author George Zeakis<zeageorge@google.com>
 * 
 */
class Tools {

    public static function sendToClient_JSON(array $data) {
        header('Content-type: application/json');
        echo json_encode($data);
    }

    /**
     *
     * @flatten multi-dimensional array
     * @param array $array
     * @return array
     */
    public static function flattenArray(array $array) {
        $ret_array = array();
        foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $value) {
            $ret_array[] = $value;
        }
        return $ret_array;
    }

    /**
     * 
     * @param string $toCheck
     * @return boolean Returns TRUE if param $toCheck only contains digits [0..9], FALSE otherwise
     */
    public static function hasOnlyDigits($toCheck) {
        $digits = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $n = (string) $toCheck;
        
        $len = strlen($n);
        
        if ($len<1) {return FALSE;}

        for ($i = 0; $i < $len; $i++) {
            if (!in_array(substr($n, $i, 1), $digits)) {
                return FALSE;
            }
        }

        return TRUE;
    }

    /**
     * 
     * @param string $sessionID
     * @param integer $min_len
     * @param integer $max_len
     * @param boolean $throwExceptionOnError
     * @return boolean
     * @throws codeExecution_FlowControlException
     */
    public static function isValidSessionID($sessionID, $min_len=26, $max_len=128, $throwExceptionOnError=FALSE){
        $validChars = array(
            'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
            'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
            '0','1','2','3','4','5','6','7','8','9',',','-',
        );
        $n = (string) $sessionID;
        
        $len = strlen($n);
        
        if ($len<$min_len || $len>$max_len) {
            if ($throwExceptionOnError) { throw new Exception("Invalid Session ID length"); }
            return FALSE;
        }

        for ($i = 0; $i < $len; $i++) {
            if (!in_array(substr($n, $i, 1), $validChars)) { 
                if ($throwExceptionOnError) { throw new Exception("Session ID contains invalid characters"); }
                return FALSE;
            }
        }

        return TRUE;
    }
}

?>
